use anyhow::ensure;
use anyhow::Result;
use log::info;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

use crate::REQWEST_CLIENT;

/// Mapping to [stock_600519_day_k.json](file:///Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/eastmoney/sample/stock_600519_day_k.json)
/// Mapping to [stock_600519_minute_1.json](file:///Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/eastmoney/sample/stock_600519_minute_1.json)
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StockKline {
    pub rc: i32,
    pub rt: i32,
    pub svr: u64,
    pub lt: i32,
    pub full: i32,
    pub dlmkts: String,
    pub data: Option<StockKlineData>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct StockKlineData {
    pub code: String,
    pub market: i32,
    pub name: String,
    pub decimal: i32,
    pub dktotal: i32,
    #[serde(rename = "preKPrice")]
    pub pre_kprice: Option<Value>,
    #[serde(rename = "prePrice")]
    pub pre_price: Option<Value>,
    #[serde(rename = "qtMiscType")]
    pub qt_misc_type: Option<Value>,
    //   时间，开盘，收盘，最高，最低，成交量，成交额，振幅，涨跌幅，涨跌额，换手率
    //  "2024-03-04,10.45,10.33,10.50,10.32,1655930,1719562862.03,1.72,-1.53,-0.16,0.85"
    pub klines: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct KlineTick {
    pub time: String, //时间，
    pub open: f64, //开盘，
    pub close: f64, //收盘，
    pub high: f64, //最高，
    pub low: f64, //最低，
    pub volume: u64, //成交量，
    pub value: f64, //成交额，
    pub amplitude: f64, //振幅，
    pub fluctuation_rate: f64, //涨跌幅，
    pub fluctuation_amount: f64, //涨跌额，
    pub turnover_rate: f64, //换手率
}

impl TryFrom<&str> for KlineTick {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        // Implement the parsing logic here to convert the string into a KlineTick struct
        // For example:
        let parts: Vec<&str> = value.split(',').collect();

        // Parse the parts and create a KlineTick instance
        let kline_tick = KlineTick {
            time: parts[0].to_string(),
            open: parts[1].parse().map_err(|e| format!("Error parsing open: {}", e))?,
            close: parts[2].parse().map_err(|e| format!("Error parsing close: {}", e))?,
            high: parts[3].parse().map_err(|e| format!("Error parsing high: {}", e))?,
            low: parts[4].parse().map_err(|e| format!("Error parsing low: {}", e))?,
            volume: parts[5].parse().map_err(|e| format!("Error parsing volume: {}", e))?,
            value: parts[6].parse().map_err(|e| format!("Error parsing value: {}", e))?,
            amplitude: parts[7].parse().map_err(|e| format!("Error parsing amplitude: {}", e))?,
            fluctuation_rate: parts[8]
                .parse()
                .map_err(|e| format!("Error parsing fluctuation_rate: {}", e))?,
            fluctuation_amount: parts[9]
                .parse()
                .map_err(|e| format!("Error parsing fluctuation_amount: {}", e))?,
            turnover_rate: parts[10]
                .parse()
                .map_err(|e| format!("Error parsing turnover_rate: {}", e))?,
        };

        Ok(kline_tick)
    }
}

/// Refer: https://quote.eastmoney.com/concept/SH600519.html?from=data#fschart-r
///
/// 分钟K线数据太老的就没有，好险只有最近几天的才有
///
/// Data: /api/qt/stock/kline/get
///
/// secid: str e.g. e.g. sh 1.600519, sz 0.000001
///
///
/// end : str,
///     结束日期， ``'20500101'`` ，表示 2050年1月1日
///
/// klt : int,
///    行情之间的时间间隔，可选示例如下
///    - ``5``      : 5 分钟 最大可以获取 1536个K线数据 / 48个K线数据/天 = 32天
///    - ``15``     : 15分钟 最大可以获取 1536个K线数据 / 48个K线数据/天 = 32天
///    - ``30``     : 30分钟 最大可以获取 1536个K线数据 / 48个K线数据/天 = 32天
///    - ``60``     : 60分钟 最大可以获取 1536个K线数据 / 48个K线数据/天 = 32天
///    - ``101``    : 日 可以获取所有数据
///    - ``102``    : 周 可以获取所有数据
///    - ``103``    : 月 可以获取所有数据
///
/// fqt : int,
///    复权方式，可选示例如下
///    - ``0`` : 不复权
///    - ``1`` : 前复权
///    - ``2`` : 后复权
///
/// lmt : int,
///    一次性获取记录个数
///
/// [北京股票](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.688016&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=1&fqt=1&beg=19000001&end=20240307&lmt=2100)
///
/// [上海ETF](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.513130&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&beg=19000001&end=20240307&lmt=2100)
///
/// [上海股票](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&beg=20240305&end=20240307&lmt=2100)
///
/// [深圳股票](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.001239&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&beg=20240305&end=20240307&lmt=2100)
///
/// [深圳ETF1分钟](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=1&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF5分钟](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=5&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF15分钟](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=15&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF30分钟](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=30&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF60分钟](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=60&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF日   ](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF周   ](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=102&fqt=1&end=20240307&lmt=100)
///
/// [深圳ETF月   ](https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=103&fqt=1&end=20240307&lmt=100)
///
pub async fn get_stock_kline(
    secid: &str,
    end: &str,
    klt: u32,
    fqt: u16,
    lmt: u32
) -> Result<StockKline> {
    ensure!(
        matches!(klt, 5 | 15 | 30 | 60 | 101 | 102 | 103),
        "(eastmoney only)klt must be in [ 5, 15, 30, 60, 101, 102, 103]"
    );

    //GET /api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240314&lmt=210&cb=quote_jp1 HTTP/1.1
    //Accept: */*
    //Accept-Encoding: gzip, deflate, br, zstd
    //Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
    //Cache-Control: no-cache
    //Connection: keep-alive
    //Cookie: qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND1=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND2=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND3=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND4=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND5=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND6=02-02%2010%3A30%3A22@%23%24%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; EMFUND7=02-26%2016%3A07%3A01@%23%24%u91D1%u9E70%u6DFB%u76C8%u7EAF%u503A%u503A%u5238A@%23%24003384; EMFUND8=02-27%2010%3A51%3A37@%23%24%u534E%u590F%u6210%u957F%u6DF7%u5408@%23%24000001; EMFUND9=02-27 13:53:07@#$%u534E%u6CF0%u67CF%u745E%u5357%u65B9%u4E1C%u82F1%u6052%u751F%u79D1%u6280%28QDII-ETF%29@%23%24513130; HAList=ty-1-600519-%u8D35%u5DDE%u8305%u53F0%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300059-%u4E1C%u65B9%u8D22%u5BCC%2Cty-0-837046-%u4EBF%u80FD%u7535%u529B%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-1-601360-%u4E09%u516D%u96F6%2Cty-1-600055-%u4E07%u4E1C%u533B%u7597%2Cty-0-159001-%u8D27%u5E01ETF%2Cty-0-161127-%u6807%u666E%u751F%u7269%u79D1%u6280LOF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=2096; st_psi=20240314144832174-113200354966-8155831817; st_asi=20240314144832174-113200354966-8155831817-web.xgnhqdy.rk-1
    //Host: push2his.eastmoney.com
    //Pragma: no-cache
    //Referer: https://quote.eastmoney.com/concept/SH600519.html?from=data
    //Sec-Fetch-Dest: script
    //Sec-Fetch-Mode: no-cors
    //Sec-Fetch-Site: same-site
    //User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
    //sec-ch-ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"
    //sec-ch-ua-mobile: ?0
    //sec-ch-ua-platform: "macOS"

    // Query String Parameters
    //
    let host = "push2his.eastmoney.com";
    // secid: 0.000001
    let ut = utils::generate_random_hex_string(32);
    let fields1 = "f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6";
    let fields2 = "f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61";
    // klt: 101
    // fqt: 1
    // end: 20240307
    // lmt: 21000
    // cb: quote_jp5

    //secid: 1.600519
    //ut: fa5fd1943c7b386f172d6893dbfba10b
    //fields1: f1,f2,f3,f4,f5,f6
    //fields2: f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61
    //klt: 5
    //fqt: 1
    //end: 20240425
    //lmt: 210
    //cb: quote_jp4

    // 分时sse: https://68.push2.eastmoney.com/api/qt/stock/trends2/sse?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f17&fields2=f51,f52,f53,f54,f55,f56,f57,f58&mpi=1000&ut=fa5fd1943c7b386f172d6893dbfba10b&secid=1.600519&ndays=1&iscr=0&iscca=0&wbp2u=1849325530509956|0|1|0|web
    //   vs钟:  https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=5&fqt=1&end=20200425&lmt=10
    //  5分钟:  https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=5&fqt=1&end=20240425&lmt=210
    // 15分钟:  https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=15&fqt=1&end=20240425&lmt=210
    // 30分钟:  https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=30&fqt=1&end=20240425&lmt=210
    // 60分钟:  https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=60&fqt=1&end=20240425&lmt=210
    // 日线:    https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240425&lmt=210
    // 周线:    https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=102&fqt=1&end=20240425&lmt=210
    // 月线:    https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=103&fqt=1&end=20240425&lmt=210

    let request_url = format!(
        "https://{host}/api/qt/stock/kline/get?secid={secid}&ut={ut}&fields1={fields1}&fields2={fields2}&klt={klt}&fqt={fqt}&end={end}&lmt={lmt}"
    );
    // 北京股票 https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.688016&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240307&lmt=210
    // 上海ETF https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.513130&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240307&lmt=210
    // 上海股票 https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.600519&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240307&lmt=210
    // 深圳股票 https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.001239&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240307&lmt=210
    // 深圳ETF https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=0.159916&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20240307&lmt=210

    info!("(get_stock_kline) request_url= {}\n", request_url);

    let response = REQWEST_CLIENT.get(request_url.clone())
        .header(reqwest::header::ACCEPT, "*.*")
        .header(reqwest::header::ACCEPT_ENCODING, "gzip, deflate, br")
        .header(reqwest::header::ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8")
        .header(reqwest::header::CACHE_CONTROL, "no-cache")
        .header(reqwest::header::CONNECTION, "keep-alive")
        // .header(reqwest::header::COOKIE, "qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=438; st_psi=20240226102321941-113200301321-9024721593")
        .header(reqwest::header::HOST, format!("{host}"))
        .header(reqwest::header::PRAGMA, "no-cache")
        // .header(reqwest::header::REFERER , "https://quote.eastmoney.com/concept/SH600519.html?from=data")
        .header(
            reqwest::header::USER_AGENT,
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
        )
        .header(
            "Sec-Ch-Ua",
            "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
        )
        .header("Sec-Ch-Ua-Mobile", "?0")
        .header("Sec-Ch-Ua-Platform", "\"macOS\"")
        .header("Sec-Fetch-Dest", "empty")
        .header("Sec-Fetch-Mode", "cors")
        .header("Sec-Fetch-Site", "same-origin")
        .send().await?;

    let body = response.text().await?;

    // println!("*** body={}\n\nhangqin\n\n", body);

    let fund: StockKline = serde_json::from_str(&body)?;

    // println!("{:?}", fund);

    Ok(fund)
}

impl StockKlineData {
    pub fn kline_ticks(&self) -> Vec<KlineTick> {
        let mut kline_ticks = Vec::new();

        for kline in &self.klines {
            if let Ok(tick) = KlineTick::try_from(kline.as_str()) {
                kline_ticks.push(tick);
            }
        }

        kline_ticks
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn test_stock_kline_with_klt() {
        let secids = [
            // "0.159001", // 深市ETF
            // "1.513130", // 上海ETF
            // "1.600519", // 上海股票
            // "1.110002", //退市可转债
            // "1.128136", //上海在线可转债
            "0.000002", //最早上市并且还在上市的股票是万科A（ 000002 ），它曾是深圳证券交易所最早上市的“五虎将”之一，上市时名为深万科，现在称为万科A。
        ]; // fund-etfs and stocks

        for secid in secids {
            let stock_klts = [5, 15, 30, 60, 101, 102, 103];
            for klt in stock_klts {
                let result = get_stock_kline(secid, "20240425", klt, 1, 10000).await;

                // println!("klt[{klt}] result={:?}\n", result);
                assert_eq!(result.is_ok(), true);
                if let Ok(StockKline { data: Some(kline_data), .. }) = result {
                    println!("klt[{klt}] kline_data.size={:?}", kline_data.klines.len());
                    for (idx, kline) in kline_data.klines.iter().enumerate() {
                        if idx > 2 {
                            break;
                        }
                        println!(
                            "\nklt[{klt}][{idx}]={:?} \n{:?}",
                            kline,
                            &kline_data.kline_ticks()[idx]
                        );
                    }
                }
            }
        }
    }

    #[tokio::test]
    async fn test_stock_kline_minute_1() {
        // let result = get_stock_kline("1.600519", "20300702", 101, 1, 200).await;
        let result = get_stock_kline("0.430017", "20300702", 101, 1, 200).await;
        let result = get_stock_kline("0.831039", "20300702", 101, 1, 200).await;

        // println!("{:?}", result);

        assert_eq!(result.is_ok(), true);
        if let Ok(estmoney_stock) = result {
            assert_eq!(estmoney_stock.data.clone().unwrap().code, "831039");
            println!(
                "estmoney_stock.data.klines[0]={:?} \n kline_ticks[0]={:?}\n",
                estmoney_stock.data.clone().unwrap().klines.first(),
                estmoney_stock.data.unwrap().kline_ticks().first()
            );
        }
    }
}
